<template>
  <div class="tab-contril">
    <!-- 默认第一个添加active属性 -->
    <div
      v-for="(item, index) in titles"
      class="tab-contril-item"
      :class="{ active: index === currentIndex }"
      :key="index"
      @click="itemClick(index)"
    >
      <span>{{ item }}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: "TabControl",
  data() {
    return {
      //  默认第一个添加active属性
      currentIndex: 0,
    };
  },
  props: {
    titles: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  methods: {
    // 点击选项卡
    itemClick(index) {
      // 每次点击把给按钮的currentIndex改成当前索引index，当2个值一样就添加active类，实现点击颜色效果
      this.currentIndex = index;
      // 通过$emit子传父把当前点击tab的index传给父组件home（index是v-for遍历的参数）
      this.$emit("getTabIndex", index);
    },
  },
};
</script>

<style lang='less'>
.tab-contril {
  display: flex;
  background-color: #fff;
  .tab-contril-item {
    flex: 1;
    text-align: center;
    height: 40px;
    line-height: 40px;
    span {
      position: relative;
      padding: 0 10px;
    }
    &.active {
      span {
        color: orange;
        &::after {
          content: "";
          position: absolute;
          bottom: -6px;
          left: 0;
          right: 0;
          width: 100%;
          height: 3px;
          background-color: orange;
        }
      }
    }
  }
}
</style>
